package com.Policing.Polling;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ListView;

import com.Policing.Adapter.look_image_adap;
import com.Policing.BaseActivity;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.Okhttps.MyOkHttp;
import com.Policing.R;
import com.Policing.Since_case.Since_case;
import com.Policing.bean.look_image_bean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hb.dialog.dialog.LoadingDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Response;

public class Step_Imag extends BaseActivity {
    //  private GridView gridView;
    private String url="http://"+ Ip_Set.IP+"/api/pointStepQuery";
    private List<look_image_bean> data = new ArrayList<>();
    private ListView listView;
    LoadingDialog loadingDialog;
    ImageView fh;
    /*   private ScrollView scroll;

       private ImageView imageView;
       private ArrayList<String> mPicList = new ArrayList<>(); //上传的图片凭证的数据源
       private GridViewAdapter mGridViewAddImgAdapter; //展示上传的图片的适配器*/
    private String pointId="";
    private MyOkHttp myOkHttp;
    @Override
    public int intiLayout() {
        return R.layout.step_imag;
    }

    @Override
    public void initView() {
        myOkHttp=new MyOkHttp(getApplicationContext());
        listView = (ListView) findViewById(R.id.imagelist);
        loadingDialog = new LoadingDialog(Step_Imag.this);
        loadingDialog.setMessage("正在加载数据..");
        loadingDialog.show();
       /* imageView = (ImageView) findViewById(R.id.fh);
        scroll = (ScrollView) findViewById(R.id.scroll);
        gridView = (GridView) findViewById(R.id.gridView);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });*/
        pointId = getIntent().getStringExtra("pointId");
        fh= (ImageView) findViewById(R.id.fh);
        fh.setOnClickListener(v -> finish());
    }

    @Override
    public void initData() {
        load();
      /*  gridView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_UP){
                    scroll.requestDisallowInterceptTouchEvent(false);
                }else{
                    scroll.requestDisallowInterceptTouchEvent(true);
                }
                return false;
            }
        });*/
    }
    //初始化展示上传图片的GridView
  /*  private void initGridView() {
        mGridViewAddImgAdapter = new GridViewAdapter(Step_Imag.this, mPicList);
        mGridViewAddImgAdapter.setIntmax(mPicList.size());
        gridView.setAdapter(mGridViewAddImgAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
               *//* if (position == parent.getChildCount() - 1) {
                    //如果“增加按钮形状的”图片的位置是最后一张，且添加了的图片的数量不超过5张，才能点击
                    if (mPicList.size() == 5) {
                        //最多添加5张图片

                    } else {
                        //添加凭证图片
                        selectPic(5 - mPicList.size());
                    }
                } else {
                    viewPluImg(position);
                }*//*
               // viewPluImg(position);

                 final Dialog  dialog = new Dialog(Step_Imag.this,R.style.FullActivity);
                WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes();
                attributes.width = WindowManager.LayoutParams.MATCH_PARENT;
                attributes.height = WindowManager.LayoutParams.MATCH_PARENT;
                dialog.getWindow().setAttributes(attributes);
                ImageView imageView= new ImageView(Step_Imag.this);
                imageView.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

                imageView.setImageBitmap(base64ToBitmap(mPicList.get(position)));
                dialog.setContentView(imageView);
                //大图的点击事件（点击让他消失）
                dialog.show();
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
            }
        });
    }
    //查看大图
    public static Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data.split(",")[1], Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    private void viewPluImg(int position) {
        Intent intent = new Intent(Step_Imag.this, PlusImageActivity.class);
        intent.putStringArrayListExtra(MainConstant.IMG_LIST, mPicList);
        intent.putExtra(MainConstant.POSITION, position);
        startActivityForResult(intent, MainConstant.REQUEST_CODE_MAIN);
    }

     *//*
    private void selectPic(int maxTotal) {
        PictureSelectorConfig.initMultiConfig(this, maxTotal);
    }

    // 处理选择的照片的地址
    private void refreshAdapter(List<LocalMedia> picList) {
        for (LocalMedia localMedia : picList) {
            //被压缩后的图片路径
            if (localMedia.isCompressed()) {
                String compressPath = localMedia.getCompressPath(); //压缩后的图片路径
                mPicList.add(compressPath); //把图片添加到将要上传的图片数组中
                mGridViewAddImgAdapter.notifyDataSetChanged();
            }
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    refreshAdapter(PictureSelector.obtainMultipleResult(data));
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    break;
            }
        }

        if (requestCode == MainConstant.REQUEST_CODE_MAIN && resultCode == MainConstant.RESULT_CODE_VIEW_IMG) {
            //查看大图页面删除了图片
            ArrayList<String> toDeletePicList = data.getStringArrayListExtra(MainConstant.IMG_LIST); //要删除的图片的集合
            mPicList.clear();
            mPicList.addAll(toDeletePicList);
            mGridViewAddImgAdapter.notifyDataSetChanged();
        }
    }*/
    private void load(){
        Map<String,String> map = new HashMap<>();
        map.put("pointId",pointId);
        map.put("source", Since_case.set().getSource());
        Log.i("source数据",Since_case.set().getSource()+"pointId"+pointId);
        myOkHttp.post(url, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                runOnUiThread(() -> {
                    loadingDialog.dismiss();
                    toastShort("加载失败！");
                });
            }

            @Override
            public void requestSuccess(Response response) throws IOException, JSONException {
                String responseData=response.body().string();
                try {
                    Log.i("datadata数据",responseData);
                    JSONObject jsonObject = new JSONObject(responseData);
                    JSONArray json = jsonObject.getJSONArray("image");
                    for (int j = 0;j<json.length();j++){
                        Bitmap bitmap =null;
                        JSONObject js = (JSONObject) json.get(j);
                        String i = js.getString("i");
                        String t = js.getString("t");
                        if (i.equals("")){
                            Log.i("jinjinjin","1");// wh  getResources().openRawResource(R.mipmap.null_po);
                            @SuppressLint("ResourceType") InputStream is = getResources().openRawResource(R.mipmap.null_po);
                            bitmap = BitmapFactory.decodeStream(is);
                        }else {
                            Log.i("jinjinjin","2");

                            byte [] input = Base64.decode(i.split(",")[1], Base64.DEFAULT);
                            bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
                        }
                        data.add(new look_image_bean(bitmap,t));
                        Log.i("datadata数据",i);

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                 Bitmap bitmap =null;
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<SiteActivity_Bean>() {}.getType();
                SiteActivity_Bean jsonBean = gson.fromJson(responseData, type);
                runOnUiThread(() -> {
                    loadingDialog.dismiss();
                    look_image_adap look_image_adaps = new look_image_adap(Step_Imag.this,R.layout.look_image,data);
                    listView.setAdapter(look_image_adaps);
                });
            }
        });
        /*HttpOkHttp.getInstance().requestPost(url, map, new HttpOkHttp.OkHttpCallBack<String>() {
            @Override
            public void requestSuccess(String s) {
                try {
                    Log.i("datadata数据",s);

                    JSONObject jsonObject = new JSONObject(s);
                    JSONArray json = jsonObject.getJSONArray("image");
                    for (int j = 0;j<json.length();j++){
                        Bitmap bitmap =null;
                        JSONObject js = (JSONObject) json.get(j);
                        String i = js.getString("i");
                        String t = js.getString("t");
                        if (i.equals("")){
                            Log.i("jinjinjin","1");
                            InputStream is = getResources().openRawResource(R.mipmap.null_po);
                            bitmap = BitmapFactory.decodeStream(is);
                        }else {
                            Log.i("jinjinjin","2");

                            byte [] input = Base64.decode(i.split(",")[1], Base64.DEFAULT);
                            bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
                        }
                        data.add(new look_image_bean(bitmap,t));
                        Log.i("datadata数据",i);

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
              *//*  Bitmap bitmap =null;
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<SiteActivity_Bean>() {}.getType();
                SiteActivity_Bean jsonBean = gson.fromJson(s, type);*//*
                runOnUiThread(() -> {
                    loadingDialog.dismiss();
                    look_image_adap look_image_adaps = new look_image_adap(Step_Imag.this,R.layout.look_image,data);
                    listView.setAdapter(look_image_adaps);
                });

            }

            @Override
            public void requestFailure(String message) {
                Log.i("datadata数据",message);
                runOnUiThread(() -> {
                    loadingDialog.dismiss();
                    toastShort("加载失败！");
                });
            }
        },String.class);*/
    }

}
